package cn.bfay.lion.jingdong.manager;

import cn.bfay.lion.jingdong.client.JdProductBaseInfoClient;
import cn.bfay.lion.jingdong.client.JdProductDiscountClient;
import cn.bfay.lion.jingdong.client.JdProductPriceClient;
import cn.bfay.lion.jingdong.client.rsp.JdProductBaseInfoRsp;
import cn.bfay.lion.jingdong.client.rsp.JdProductCouponResult;
import cn.bfay.lion.jingdong.client.rsp.JdProductCouponRsp;
import cn.bfay.lion.jingdong.client.rsp.JdProductPriceRsp;
import cn.bfay.lion.jingdong.client.rsp.JdProductPromotionResult;
import cn.bfay.lion.jingdong.client.rsp.JdProductPromotionRsp;
import cn.bfay.lion.jingdong.enums.CouponType;
import cn.bfay.lion.jingdong.enums.PromotionType;
import cn.bfay.lion.util.DateUtils;
import cn.bfay.lion.util.FormatUtils;
import cn.bfay.lion.util.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * JdManager.
 *
 * @author wangjiannan
 */
@Slf4j
@Component
public class JdManager {
    @Resource
    private JdProductBaseInfoClient jdProductBaseInfoClient;
    @Resource
    private JdProductPriceClient jdProductPriceClient;
    @Resource
    private JdProductDiscountClient jdProductDiscountClient;

    /**
     * 获取商品基本信息.
     *
     * @param skuid 商品id
     * @return {@link JdProductBaseInfoRsp}
     */
    public JdProductBaseInfoRsp getJdProductBaseInfoRsp(String skuid) {
        String content = jdProductBaseInfoClient.getContent(skuid);
        content = content.substring(content.indexOf(":") + 1, content.length() - 1);
        JdProductBaseInfoRsp jdProductBaseInfoRsp = JsonUtils.json2Bean(content, JdProductBaseInfoRsp.class);
        jdProductBaseInfoRsp.setSkuid(skuid);
        return jdProductBaseInfoRsp;
    }

    /**
     * 获取商品基本信息.
     *
     * @param skuids 商品id
     * @return {@link List<JdProductBaseInfoRsp>}
     */
    public List<JdProductBaseInfoRsp> getJdProductBaseInfoRsps(List<String> skuids) {
        String content = jdProductBaseInfoClient.getContent(Joiner.on(",").join(skuids));
        content = content.substring(1, content.length() - 1);
        List<String> infos = Splitter.on("},").splitToList(content);
        List<JdProductBaseInfoRsp> jdProductBaseInfoRsps = new ArrayList<>();
        infos.forEach(info -> {
            info = info + "}";
            String infoStart = info.substring(1, info.indexOf(":") - 1);
            String infoEnd = info.substring(info.indexOf(":") + 1);
            JdProductBaseInfoRsp jdProductBaseInfoRsp = JsonUtils.json2Bean(infoEnd, JdProductBaseInfoRsp.class);
            jdProductBaseInfoRsp.setSkuid(infoStart);
            jdProductBaseInfoRsps.add(jdProductBaseInfoRsp);
        });
        return jdProductBaseInfoRsps;
    }

    /**
     * 获取商品价格.
     *
     * @param skuid 商品id
     * @return {@link JdProductPriceRsp}
     */
    public JdProductPriceRsp getJdProductPriceRsp(String skuid) {
        String content = jdProductPriceClient.getContent(skuid);
        content = content.substring(1, content.length() - 1);
        JdProductPriceRsp jdProductPriceRsp = JsonUtils.json2Bean(content, JdProductPriceRsp.class);
        jdProductPriceRsp.setSkuid(jdProductPriceRsp.getSkuid().substring(2));
        Double normalPrice = jdProductPriceRsp.getNormalPrice();
        jdProductPriceRsp.setNormalPrice(FormatUtils.formatDouble(normalPrice));
        Double plusPrice = jdProductPriceRsp.getPlusPrice();
        jdProductPriceRsp.setPlusPrice(FormatUtils.formatDouble(plusPrice == null ? normalPrice : plusPrice));
        return jdProductPriceRsp;
    }

    /**
     * 获取商品价格.
     *
     * @param skuids 商品id
     * @return {@link List<JdProductPriceRsp>}
     */
    public List<JdProductPriceRsp> getJdProductPriceRsps(List<String> skuids) {
        String content = jdProductPriceClient.getContent(Joiner.on(",").join(skuids));
        TypeReference<List<JdProductPriceRsp>> typeReference = new TypeReference<List<JdProductPriceRsp>>() {
        };
        List<JdProductPriceRsp> jdProductPriceRsps = JsonUtils.json2Bean(content, typeReference);
        for (JdProductPriceRsp jdProductPriceRsp : jdProductPriceRsps) {
            jdProductPriceRsp.setSkuid(jdProductPriceRsp.getSkuid().substring(2));
            Double normalPrice = jdProductPriceRsp.getNormalPrice();
            jdProductPriceRsp.setNormalPrice(FormatUtils.formatDouble(normalPrice));
            Double plusPrice = jdProductPriceRsp.getPlusPrice();
            jdProductPriceRsp.setPlusPrice(FormatUtils.formatDouble(plusPrice == null ? normalPrice : plusPrice));
        }
        return jdProductPriceRsps;
    }

    /**
     * 获取商品促销.
     *
     * @param skuid 商品id
     * @return {@link JdProductPromotionRsp}
     */
    public JdProductPromotionRsp getJdProductPromotionRsp(String skuid) {
        String content = jdProductDiscountClient.getPromotionContent("https://item.m.jd.com/", skuid);
        // callback({"errcode":"0","errmsg":"","data":[{"id":"2384709","pis":[{"d":"1539705599","subextinfo":"{\"extType\":15,\"subExtType\":23,\"subRuleList\":[{\"needNum\":\"2\",\"rebate\":\"8\",\"subRuleList\":[]},{\"needNum\":\"3\",\"rebate\":\"7\",\"subRuleList\":[]}]}","19":"满2件，总价打8折；满3件，总价打7折","adurl":"http://sale.jd.com/act/BpSkJQaq657MCIiF.html","pid":"237107540_10","st":"1539014400","customtag":"{}","ori":"1"},{"d":"1541001599","subextinfo":"{\"extType\":2,\"needMoney\":\"129\",\"rewardMoney\":\"10\",\"subExtType\":9,\"subRuleList\":[]}","adurl":"https://mall.jd.com/index-1000100622.html","15":"每满129元，可减10元现金","pid":"236319400_10","st":"1538323200","customtag":"{}","ori":"1"}]}]})
        content = content.substring(content.indexOf("(") + 1, content.length() - 1);
        // {"errcode":"0","errmsg":"","data":[{"pis":[{"15":"每满129元，可减10元现金","d":"1539673572","ori":"1","st":"1538323200","adurl":"https://mall.jd.com/index-1000100622.html","pid":"236319400_10","subextinfo":"{\"extType\":2,\"needMoney\":\"129\",\"rewardMoney\":\"10\",\"subExtType\":9,\"subRuleList\":[]}","customtag":"{}"},{"19":"满2件，总价打8折；满3件，总价打7折","d":"1539673553","ori":"1","st":"1539014400","adurl":"http://sale.jd.com/act/BpSkJQaq657MCIiF.html","pid":"237107540_10","subextinfo":"{\"extType\":15,\"subExtType\":23,\"subRuleList\":[{\"needNum\":\"2\",\"rebate\":\"8\",\"subRuleList\":[]},{\"needNum\":\"3\",\"rebate\":\"7\",\"subRuleList\":[]}]}","customtag":"{}"}],"id":"2384709"}]}
        JdProductPromotionResult jdProductPromotionResult =
            JsonUtils.json2Bean(content, JdProductPromotionResult.class);
        JdProductPromotionRsp jdProductPromotionRsp = new JdProductPromotionRsp();
        if (!StringUtils.equals("0", jdProductPromotionResult.getErrcode())) {
            return jdProductPromotionRsp;
        }
        List<JdProductPromotionResult.ResultData> data = jdProductPromotionResult.getData();
        if (CollectionUtils.isEmpty(data)) {
            return jdProductPromotionRsp;
        }
        jdProductPromotionRsp.setSkuid(data.get(0).getId());
        List<JdProductPromotionResult.ResultData.PromotionInfo> pis = data.get(0).getPis();
        List<JdProductPromotionRsp.JdProductPromotion> jdProductPromotions = new ArrayList<>();
        pis.forEach(pi -> {
            if (StringUtils.isNotBlank(pi.getSt()) && LocalDateTime.now()
                .isBefore(DateUtils.converTimestampToLocalDateTime(Long.parseLong(pi.getSt() + "000")))) {
                log.info("还没到时间，不能使用当前促销.skuid={},st={},timeDesc={}", skuid, pi.getSt(),
                    DateUtils.converTimestampToString(Long.parseLong(pi.getSt() + "000"), DateUtils.PATTERN_DEFAULT));
            } else {
                // 处理plus价格和plus的折扣
                String customtag = pi.getCustomtag();
                if (StringUtils.isNotBlank(customtag) && !"{}".equals(customtag)) {
                    processCustomtag(customtag, pi.get_26(), jdProductPromotionRsp);
                }
                String subextinfo = pi.getSubextinfo();
                if (StringUtils.isNotBlank(subextinfo)) {
                    processSubextinfo(subextinfo, jdProductPromotions);
                }
            }
        });
        jdProductPromotionRsp.setJdProductPromotions(jdProductPromotions);
        return jdProductPromotionRsp;
    }

    /**
     * 获取商品促销.
     *
     * @param skuids 商品id
     * @return {@link List<JdProductPromotionRsp>}
     */
    public List<JdProductPromotionRsp> getJdProductPromotionRsps(List<String> skuids) {
        String content = jdProductDiscountClient.getPromotionContent("https://item.m.jd.com/", Joiner.on(",").join(skuids));
        // callback({"errcode":"0","errmsg":"","data":[{"id":"2384709","pis":[{"d":"1539705599","subextinfo":"{\"extType\":15,\"subExtType\":23,\"subRuleList\":[{\"needNum\":\"2\",\"rebate\":\"8\",\"subRuleList\":[]},{\"needNum\":\"3\",\"rebate\":\"7\",\"subRuleList\":[]}]}","19":"满2件，总价打8折；满3件，总价打7折","adurl":"http://sale.jd.com/act/BpSkJQaq657MCIiF.html","pid":"237107540_10","st":"1539014400","customtag":"{}","ori":"1"},{"d":"1541001599","subextinfo":"{\"extType\":2,\"needMoney\":\"129\",\"rewardMoney\":\"10\",\"subExtType\":9,\"subRuleList\":[]}","adurl":"https://mall.jd.com/index-1000100622.html","15":"每满129元，可减10元现金","pid":"236319400_10","st":"1538323200","customtag":"{}","ori":"1"}]}]})
        content = content.substring(content.indexOf("(") + 1, content.length() - 1);
        // {"errcode":"0","errmsg":"","data":[{"pis":[{"15":"每满129元，可减10元现金","d":"1539673572","ori":"1","st":"1538323200","adurl":"https://mall.jd.com/index-1000100622.html","pid":"236319400_10","subextinfo":"{\"extType\":2,\"needMoney\":\"129\",\"rewardMoney\":\"10\",\"subExtType\":9,\"subRuleList\":[]}","customtag":"{}"},{"19":"满2件，总价打8折；满3件，总价打7折","d":"1539673553","ori":"1","st":"1539014400","adurl":"http://sale.jd.com/act/BpSkJQaq657MCIiF.html","pid":"237107540_10","subextinfo":"{\"extType\":15,\"subExtType\":23,\"subRuleList\":[{\"needNum\":\"2\",\"rebate\":\"8\",\"subRuleList\":[]},{\"needNum\":\"3\",\"rebate\":\"7\",\"subRuleList\":[]}]}","customtag":"{}"}],"id":"2384709"}]}
        JdProductPromotionResult jdProductPromotionResult =
            JsonUtils.json2Bean(content, JdProductPromotionResult.class);
        if (!StringUtils.equals("0", jdProductPromotionResult.getErrcode())) {
            return new ArrayList<>();
        }
        List<JdProductPromotionResult.ResultData> data = jdProductPromotionResult.getData();
        if (CollectionUtils.isEmpty(data)) {
            return new ArrayList<>();
        }

        List<JdProductPromotionRsp> jdProductPromotionRsps = new ArrayList<>();
        for (JdProductPromotionResult.ResultData datum : data) {
            JdProductPromotionRsp jdProductPromotionRsp = new JdProductPromotionRsp();
            String skuid = datum.getId();
            jdProductPromotionRsp.setSkuid(skuid);
            List<JdProductPromotionRsp.JdProductPromotion> jdProductPromotions = new ArrayList<>();
            List<JdProductPromotionResult.ResultData.PromotionInfo> pis = datum.getPis();
            pis.forEach(pi -> {
                if (StringUtils.isNotBlank(pi.getSt()) && LocalDateTime.now()
                    .isBefore(DateUtils.converTimestampToLocalDateTime(Long.parseLong(pi.getSt() + "000")))) {
                    log.info("还没到时间，不能使用当前促销.skuid={},st={},timeDesc={}", skuid, pi.getSt(),
                        DateUtils.converTimestampToString(Long.parseLong(pi.getSt() + "000"), DateUtils.PATTERN_DEFAULT));
                } else {
                    // 处理plus价格和plus的折扣
                    String customtag = pi.getCustomtag();
                    if (StringUtils.isNotBlank(customtag) && !"{}".equals(customtag)) {
                        processCustomtag(customtag, pi.get_26(), jdProductPromotionRsp);
                    }
                    String subextinfo = pi.getSubextinfo();
                    if (StringUtils.isNotBlank(subextinfo)) {
                        processSubextinfo(subextinfo, jdProductPromotions);
                    }
                }
            });
            jdProductPromotionRsp.setJdProductPromotions(jdProductPromotions);
            jdProductPromotionRsps.add(jdProductPromotionRsp);
        }
        return jdProductPromotionRsps;
    }

    private void processCustomtag(String customtag, String _26, JdProductPromotionRsp jdProductPromotionRsp) {
        JdProductPromotionResult.Customtag cus =
            JsonUtils.json2Bean(customtag, JdProductPromotionResult.Customtag.class);
        String price = cus.getPrice();
        if (StringUtils.isNotEmpty(price)) {
            if (StringUtils.isNotBlank(_26) && _26.contains("@@")) {
                log.info("不使用customtag中的价格");
            } else {
                jdProductPromotionRsp.setPrice(Double.valueOf(price));
            }
        }
        String discount = cus.getDiscount();
        if (StringUtils.isNotEmpty(discount)) {
            jdProductPromotionRsp.setDiscount(Double.valueOf(discount) / 10.0);
        }
    }

    private void processSubextinfo(String subextinfo,
                                   List<JdProductPromotionRsp.JdProductPromotion> jdProductPromotions) {
        JdProductPromotionResult.Subextinfo si =
            JsonUtils.json2Bean(subextinfo, JdProductPromotionResult.Subextinfo.class);
        if (si != null) {
            if ((si.getExtType() == 2 && si.getSubExtType() == 8) ||
                (si.getExtType() == 2 && si.getSubExtType() == 9)) {
                // 每满减 每满减 2、8 或2、9   needMoney=199, rewardMoney=100
                JdProductPromotionRsp.JdProductPromotion gp = new JdProductPromotionRsp.JdProductPromotion();
                gp.setType(PromotionType.EVERY_FULL_MONEY_MINUS_MONEY.getCode());
                gp.setNeedMoney(Double.valueOf(si.getNeedMoney()));
                gp.setRewardMoney(Double.valueOf(si.getRewardMoney()));
                gp.setPromotion((gp.getNeedMoney() - gp.getRewardMoney()) / gp.getNeedMoney());
                jdProductPromotions.add(gp);
            } else if ((si.getExtType() == 1 && si.getSubExtType() == 1) ||
                (si.getExtType() == 6 && si.getSubExtType() == 14)) {
                // 满减  1、1或6/14     subRuleList=[{"needMoney":"99","subRuleList":[],"subRuleType":1,"rewardMoney":"20"}]
                si.getSubRuleList().forEach(e -> {
                    JdProductPromotionRsp.JdProductPromotion gp = new JdProductPromotionRsp.JdProductPromotion();
                    gp.setType(PromotionType.FULL_MONEY_MINUS_MONEY.getCode());
                    gp.setNeedMoney(Double.valueOf(e.getNeedMoney()));
                    gp.setRewardMoney(Double.valueOf(e.getRewardMoney()));
                    gp.setPromotion((gp.getNeedMoney() - gp.getRewardMoney()) / gp.getNeedMoney());
                    jdProductPromotions.add(gp);
                });
            } else if (si.getExtType() == 15 && si.getSubExtType() == 23) {
                // 满件 折扣  15、23
                si.getSubRuleList().forEach(e -> {
                    JdProductPromotionRsp.JdProductPromotion gp = new JdProductPromotionRsp.JdProductPromotion();
                    gp.setType(PromotionType.FULL_COUNT_DISCOUNT.getCode());
                    gp.setNeedNum(Double.valueOf(e.getNeedNum()));
                    gp.setRebate(Double.valueOf(e.getRebate()));
                    gp.setPromotion(gp.getRebate() / 10.0);
                    jdProductPromotions.add(gp);
                });
            } else if (si.getExtType() == 8 && si.getSubExtType() == 13) {
                // 满钱 折扣  8、13
                JdProductPromotionRsp.JdProductPromotion gp = new JdProductPromotionRsp.JdProductPromotion();
                gp.setType(PromotionType.FULL_MONEY_DISCOUNT.getCode());
                gp.setNeedMoney(Double.valueOf(si.getNeedMoney()));
                gp.setRebate((100 - Double.valueOf(si.getPercent())) / 10);
                gp.setPromotion(gp.getRebate() / 10.0);
                jdProductPromotions.add(gp);
            }
        }
    }

    /**
     * 获取商品优惠.
     *
     * @param skuid 商品id
     * @return {@link JdProductCouponRsp >}
     */
    public JdProductCouponRsp getJdProductCouponRsp(String skuid) {
        String referer = "https://item.m.jd.com/product/" + skuid + ".html";
        String couponContent2 = jdProductDiscountClient.getCouponContent(referer, "3", "111", skuid, "8888");
        List<JdProductCouponRsp.JdProductCoupon> jdProductBasesCoupons = convertCoupon(skuid, couponContent2);
        JdProductCouponRsp jdProductCouponRsp = new JdProductCouponRsp();
        jdProductCouponRsp.setSkuid(skuid);
        jdProductCouponRsp.setJdProductCoupons(jdProductBasesCoupons);
        return jdProductCouponRsp;
    }

    private List<JdProductCouponRsp.JdProductCoupon> convertCoupon(String skuid, String couponContent) {
        JdProductCouponResult jdProductCouponResult = JsonUtils.json2Bean(couponContent, JdProductCouponResult.class);
        List<JdProductCouponRsp.JdProductCoupon> jdProductCoupons = jdProductCouponResult.getCoupons();
        List<JdProductCouponRsp.JdProductCoupon> jdProductCouponsNew = new ArrayList<>();
        if (!CollectionUtils.isEmpty(jdProductCoupons)) {
            jdProductCoupons.forEach(item -> {
                String timeDesc = item.getTimeDesc();
                String start;
                if (timeDesc.contains("有效期")) {
                    start = StringUtils.substringBetween(timeDesc, "有效期", "至");
                } else {
                    start = StringUtils.substringBefore(timeDesc, "-").replace(".", "-");
                }
                if (StringUtils.isNotBlank(start) &&
                    LocalDateTime.now().isBefore(DateUtils.parseLongTime1(processTime(start)))) {
                    log.info("还没到时间，不能使用当前优惠.skuid={},timeDesc={},processTime={}", skuid, item.getTimeDesc(),
                        processTime(start));
                } else {
                    if ("0".equals(item.getCouponstyle())) {
                        item.setType(CouponType.FULL_MONEY_MINUS_MONEY.getCode());
                        item.setCoupon((item.getQuota() - item.getDiscount()) / item.getQuota());
                        jdProductCouponsNew.add(item);
                    } else if ("3".equals(item.getCouponstyle())) {
                        item.setType(CouponType.FULL_MONEY_DISCOUNT.getCode());
                        Double discount = item.getDiscountdesc().getInfo().get(0).getDiscount();
                        item.setCoupon(discount);
                        item.setDiscount(discount * 10);
                        jdProductCouponsNew.add(item);
                    } else {
                        log.warn("无匹配,请排查......");
                    }
                }
            });
        }
        return jdProductCouponsNew;
    }

    private String processTime(String input) {
        // eg:自领取后10天内有效,即当前可用
        if (input.startsWith("自领取后")) {
            return "1999-12-1200:00:00";
        }

        //"2019-12-1200:00:00"
        int length = input.length();
        if (length == 10) {
            return input + "00:00:00";
        } else if (length == 12) {
            return input + ":00:00";
        } else if (length == 15) {
            return input + ":00";
        } else if (length == 18) {
            return input;
        } else {
            return "2099-12-1200:00:00";
        }
    }
}
